PROJECTENGRAM

ONE-DIMENSIONAL ARRAYS (1D ARRAYS)

One-Dimensional Arrays (1D Arrays)

Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Structured Programming #◇Memory Management


◇Overview

dataType arrayName[arraySize];

◇Details / Theory

Declaration

Syntax:

『』
C
dataType arrayName[arraySize];

 `dataType`: Type of elements (e.g., `int`, `float`, `char`)
 `arrayName`: Name of the array
 `arraySize`: Positive integer constant

**Examples**:

```c
int numbers[10];
float prices[5];
char name[30];

Memory Allocation:
If int takes 4 bytes, then:

『』
C
int numbers[10]; // allocates 10 × 4 = 40 bytes

Initialization

Syntax:

『』
C
dataType arrayName[arraySize] = {value1, value2, ..., valueN};

Examples:

『』
C
int marks[5] = {10, 15, 12, 18, 17};
float temps[] = {23.5f, 24.0f, 22.8f};
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char message[] = "Hello";

Uninitialized elements:

『』
C
int data[5] = {1, 2}; // remaining values depend on storage type

Personal Note: Always initialize arrays to avoid garbage values.


Accessing Elements

Arrays are zero-indexed.

Syntax:

『』
C
arrayName[index]

Examples:

『』
C
int scores[3];
scores[0] = 90;
scores[1] = 85;
scores[2] = 92;

Out-of-Bounds Access:
Accessing indices outside 0 to arraySize - 1 results in undefined behavior.

Personal Note: This is a common security risk. Be cautious with loop limits.


Traversing Arrays

Forward Traversal:

『』
C
for (int i = 0; i < 5; i++) {
    printf("%d\n", values[i]);
}

Backward Traversal:

『』
C
for (int i = 4; i >= 0; i--) {
    printf("%d\n", values[i]);
}

◇Common Pitfalls

Off-by-one errors — valid indices for arr[n] are 0 to n-1; accessing arr[n] is out of bounds Forgetting to initialize all elements — uninitialized local arrays contain garbage values in C Using <= instead of < in traversal loops — for (i = 0; i <= n; i++) accesses one element past the array Reversing traversal direction without adjusting bounds — backward traversal starts at n-1 and ends at 0 (inclusive)

◇Summary

TL;DR — 1D arrays are declared as type name[size], zero-indexed (0 to size-1). Initialize with {} or a loop. Traverse forward (i = 0 to n-1) or backward (i = n-1 to 0). Always guard against out-of-bounds access.

Related: Source / Reference:

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

Which best describes a 1D array?

Q2

How do you access the very first element of a 1D array named list?

Q3

In a 1D array of size N, what is the index of the last element?